﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LightLog.Code;
using LightLog.Framework.Extensions;
using Microsoft.AspNetCore.Mvc.Filters;
using LightLog.Model.Output;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using Serilog;

namespace LightLogApi.Code.Filter
{

    /// <summary>
    /// 异常拦截
    /// </summary>
    /// <see cref="LightLogApi.Code.GlobalExceptionConfiguration"/>
    [Obsolete("采用GlobalExceptionConfiguration方式拦截全局异常")]
    public class ApiExceptionFilter : IExceptionFilter, IAsyncExceptionFilter
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            IResponseOutput data;
            int httpCode = (int)LightLog.Model.Config.StatusCodes.系统内部错误;
            //if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))//内部解析时jwt失效异常
            //{
            //    httpCode = (int)YuShen.Model.Config.StatusCodes.未登录;
            //    data = ResponseOutput.NotOk<string>("认证错误", code: httpCode);
            //}
            //else
            {
                string num = Guid.NewGuid().ToString("N");
                Log.Error(context.Exception.GetExceptionMsg("异常编号:" + num));
                data = ResponseOutput.NotOk<string>("服务器异常,异常编号:" + num, code: httpCode);
            }
            context.Result = new InternalServerErrorResult(data);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task OnExceptionAsync(ExceptionContext context)
        {
            // 如果异常没有被处理则进行处理
            if (context.ExceptionHandled == false)
            {
                OnException(context);
            }
            // 设置为true，表示异常已经被处理了
            context.ExceptionHandled = true;
            return Task.CompletedTask;
        }
    }

    /// <summary>
    /// 
    /// </summary>
    public class InternalServerErrorResult : ObjectResult
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="value"></param>
        public InternalServerErrorResult(object value) : base(value)
        {
            StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError;
        }
    }

}
/*  //添加设置
  services.AddControllers(options =>
                {
                    //全局异常拦截
                    options.Filters.Add(new ApiExceptionFilterAttribute());
                })
 */